<template>
  <div class="p-6 space-y-6">
    <!-- 页面标题 -->
    <div class="flex items-center justify-between">
      <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-200">角色管理</h2>
      <button @click="showAddDialog = true" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        新增角色
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="card">
      <div class="flex items-center gap-4">
        <div class="flex-1">
          <input v-model="searchQuery" type="text" placeholder="搜索角色名称..." class="input" />
        </div>
        <select v-model="statusFilter" class="input w-40">
          <option value="">全部状态</option>
          <option value="active">启用</option>
          <option value="inactive">禁用</option>
        </select>
        <button @click="searchRoles" class="btn-primary">搜索</button>
        <button @click="resetSearch" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 角色列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-200 dark:border-gray-700">
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">角色信息</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">权限数量</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">用户数量</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">状态</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">创建时间</th>
              <th class="text-left py-3 px-4 font-semibold text-gray-900 dark:text-gray-200">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="role in filteredRoles"
              :key="role.id"
              class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50">
              <td class="py-4 px-4">
                <div class="flex items-center gap-3">
                  <div
                    class="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                    </svg>
                  </div>
                  <div>
                    <p class="font-medium text-gray-900 dark:text-gray-200">{{ role.name }}</p>
                    <p class="text-sm text-gray-600 dark:text-gray-400">{{ role.description }}</p>
                  </div>
                </div>
              </td>
              <td class="py-4 px-4 text-gray-900 dark:text-gray-200">{{ role.permissionCount }}个</td>
              <td class="py-4 px-4 text-gray-900 dark:text-gray-200">{{ role.userCount }}人</td>
              <td class="py-4 px-4">
                <span
                  :class="[
                    'px-2 py-1 text-sm rounded-full',
                    role.status === 'active'
                      ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'
                      : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200',
                  ]">
                  {{ role.status === 'active' ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="py-4 px-4 text-gray-900 dark:text-gray-200">{{ role.createTime }}</td>
              <td class="py-4 px-4">
                <div class="flex items-center gap-2">
                  <button @click="editRole(role)" class="btn-secondary text-sm">编辑</button>
                  <button
                    @click="managePermissions(role)"
                    class="text-sm bg-purple-600 text-white rounded px-3 py-1 hover:bg-purple-700 transition-colors">
                    权限
                  </button>
                  <button
                    @click="toggleRoleStatus(role)"
                    :class="[
                      'text-sm rounded px-3 py-1 transition-colors',
                      role.status === 'active'
                        ? 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-800'
                        : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 hover:bg-green-200 dark:hover:bg-green-800',
                    ]">
                    {{ role.status === 'active' ? '禁用' : '启用' }}
                  </button>
                  <button
                    @click="deleteRole(role)"
                    class="text-sm bg-red-600 text-white rounded px-3 py-1 hover:bg-red-700 transition-colors">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Element Plus 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRoles"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination" />
      </div>
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog v-model="showAddDialog" :title="editingRole ? '编辑角色' : '新增角色'" width="500px">
      <form @submit.prevent="saveRole" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">角色名称</label>
          <input v-model="roleForm.name" type="text" class="input" required />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">角色描述</label>
          <textarea v-model="roleForm.description" rows="3" class="input resize-none"></textarea>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">状态</label>
          <select v-model="roleForm.status" class="input">
            <option value="active">启用</option>
            <option value="inactive">禁用</option>
          </select>
        </div>
      </form>
      <template #footer>
        <div class="flex justify-end gap-3">
          <button @click="showAddDialog = false" class="btn-secondary">取消</button>
          <button @click="saveRole" class="btn-primary">保存</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-role">
import { ref, computed } from 'vue'

defineOptions({ name: 'role' })

const searchQuery = ref('')
const statusFilter = ref('')
const showAddDialog = ref(false)
const editingRole = ref<any>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRoles = ref(50)

const roleForm = ref({
  name: '',
  description: '',
  status: 'active',
})

// 模拟角色数据
const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    description: '拥有系统所有权限，可以管理所有功能模块',
    permissionCount: 156,
    userCount: 2,
    status: 'active',
    createTime: '2023-01-01 00:00:00',
  },
  {
    id: 2,
    name: '系统管理员',
    description: '负责系统日常维护和用户管理',
    permissionCount: 89,
    userCount: 5,
    status: 'active',
    createTime: '2023-01-15 10:30:00',
  },
  {
    id: 3,
    name: '内容编辑',
    description: '负责内容管理和编辑工作',
    permissionCount: 45,
    userCount: 12,
    status: 'active',
    createTime: '2023-02-01 14:20:00',
  },
  {
    id: 4,
    name: '普通用户',
    description: '基础功能使用权限',
    permissionCount: 23,
    userCount: 156,
    status: 'active',
    createTime: '2023-02-15 09:15:00',
  },
])

const filteredRoles = computed(() => {
  let result = roles.value

  if (searchQuery.value) {
    result = result.filter(
      (role) =>
        role.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        role.description.toLowerCase().includes(searchQuery.value.toLowerCase()),
    )
  }

  if (statusFilter.value) {
    result = result.filter((role) => role.status === statusFilter.value)
  }

  return result
})

function searchRoles() {
  console.log('搜索角色:', searchQuery.value)
}

function resetSearch() {
  searchQuery.value = ''
  statusFilter.value = ''
}

function editRole(role: any) {
  editingRole.value = role
  roleForm.value = { ...role }
  showAddDialog.value = true
}

function saveRole() {
  if (editingRole.value) {
    // 更新角色
    const index = roles.value.findIndex((r) => r.id === editingRole.value!.id)
    if (index !== -1) {
      roles.value[index] = { ...roles.value[index], ...roleForm.value }
    }
  } else {
    // 新增角色
    const newRole = {
      id: Date.now(),
      ...roleForm.value,
      permissionCount: 0,
      userCount: 0,
      createTime: new Date().toLocaleString(),
    }
    roles.value.push(newRole)
  }

  showAddDialog.value = false
  editingRole.value = null
  roleForm.value = { name: '', description: '', status: 'active' }
}

function managePermissions(role: any) {
  console.log('管理权限:', role.name)
}

function toggleRoleStatus(role: any) {
  role.status = role.status === 'active' ? 'inactive' : 'active'
}

function deleteRole(role: any) {
  if (confirm('确定要删除这个角色吗？')) {
    roles.value = roles.value.filter((r) => r.id !== role.id)
  }
}

function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}

function handleCurrentChange(page: number) {
  currentPage.value = page
}
</script>

<style scoped>
.custom-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgb(107 114 128);
  --el-pagination-border-radius: 8px;
  --el-pagination-button-color: rgb(107 114 128);
  --el-pagination-button-bg-color: transparent;
  --el-pagination-button-disabled-color: rgb(156 163 175);
  --el-pagination-button-disabled-bg-color: transparent;
  --el-pagination-hover-color: rgb(59 130 246);
  --el-pagination-hover-bg-color: rgb(239 246 255);
}

.dark .custom-pagination {
  --el-pagination-text-color: rgb(156 163 175);
  --el-pagination-button-color: rgb(156 163 175);
  --el-pagination-hover-color: rgb(96 165 250);
  --el-pagination-hover-bg-color: rgb(30 58 138);
}
</style>
